extends Panel

signal panel_closed

var log_system: LogSystem
var current_filter_level: int = 0
var current_filter_context: String = ""
var current_search_text: String = ""
var log_entries: Array = []

func _ready():
	visible = false
	
	# 设置默认状态
	$VBoxContainer/ScrollContainer/LogTextEdit.syntax_highlighter = null
	update_status_bar()

func show_panel(log_sys: LogSystem):
	log_system = log_sys
	refresh_logs()
	visible = true

func hide_panel():
	visible = false
	panel_closed.emit()

func refresh_logs():
	if not log_system:
		$VBoxContainer/ScrollContainer/LogTextEdit.text = "日志系统未初始化"
		return
	
	# 读取日志文件
	var log_file_path = log_system.log_file_path
	if not FileAccess.file_exists(log_file_path):
		$VBoxContainer/ScrollContainer/LogTextEdit.text = "日志文件不存在: " + log_file_path
		return
	
	var file = FileAccess.open(log_file_path, FileAccess.READ)
	if not file:
		$VBoxContainer/ScrollContainer/LogTextEdit.text = "无法打开日志文件: " + log_file_path
		return
	
	# 读取所有日志条目
	log_entries.clear()
	while not file.eof_reached():
		var line = file.get_line()
		if line.strip_edges() != "":
			log_entries.append(line)
	
	# 应用过滤器并显示
	apply_filters()
	update_status_bar()

func apply_filters():
	var filtered_entries = []
	var level_names = ["DEBUG", "INFO", "WARNING", "ERROR"]
	
	for entry in log_entries:
		# 级别过滤
		if current_filter_level < 4:  # 4 是 NONE，表示不显示任何日志
			var level_found = false
			for i in range(current_filter_level, level_names.size()):
				if entry.contains("[" + level_names[i] + "]"):
					level_found = true
					break
			
			if not level_found:
				continue
		
		# 上下文过滤
		if current_filter_context != "" and not entry.contains("[" + current_filter_context + "]"):
			continue
		
		# 搜索文本过滤
		if current_search_text != "" and not entry.to_lower().contains(current_search_text.to_lower()):
			continue
		
		filtered_entries.append(entry)
	
	# 显示过滤后的日志
	var text = ""
	for entry in filtered_entries:
		# 为不同级别的日志添加颜色
		var colored_entry = entry
		if entry.contains("[DEBUG]"):
			colored_entry = entry.replace("[DEBUG]", "[color=#808080][DEBUG][/color]")
		elif entry.contains("[INFO]"):
			colored_entry = entry.replace("[INFO]", "[color=#008000][INFO][/color]")
		elif entry.contains("[WARNING]"):
			colored_entry = entry.replace("[WARNING]", "[color=#FFA500][WARNING][/color]")
		elif entry.contains("[ERROR]"):
			colored_entry = entry.replace("[ERROR]", "[color=#FF0000][ERROR][/color]")
		
		text += colored_entry + "\n"
	
	$VBoxContainer/ScrollContainer/LogTextEdit.text = text
	
	# 滚动到底部
	$VBoxContainer/ScrollContainer/LogTextEdit.scroll_vertical = $VBoxContainer/ScrollContainer/LogTextEdit.get_line_count()

func update_status_bar():
	var filtered_count = $VBoxContainer/ScrollContainer/LogTextEdit.get_line_count()
	var total_count = log_entries.size()
	$VBoxContainer/StatusBar/StatusLabel.text = "日志条目: %d / %d" % [filtered_count, total_count]

func clear_logs():
	if not log_system:
		return
	
	# 清空日志文件
	var file = FileAccess.open(log_system.log_file_path, FileAccess.WRITE)
	if file:
		file.store_string("")
		file.close()
	
	# 清空日志条目
	log_entries.clear()
	$VBoxContainer/ScrollContainer/LogTextEdit.text = ""
	update_status_bar()
	
	# 添加清空日志的记录
	log_system.info("日志已被手动清空", "LogViewer")
	refresh_logs()

func export_logs():
	if log_entries.size() == 0:
		return
	
	# 导出日志到用户选择的位置
	var datetime = Time.get_datetime_dict_from_system()
	var timestamp = "%04d%02d%02d_%02d%02d%02d" % [
		datetime.year, datetime.month, datetime.day,
		datetime.hour, datetime.minute, datetime.second
	]
	
	var export_path = "user://exported_log_" + timestamp + ".txt"
	var file = FileAccess.open(export_path, FileAccess.WRITE)
	if file:
		for entry in log_entries:
			file.store_line(entry)
		file.close()
		
		log_system.info("日志已导出到: " + export_path, "LogViewer")
		$VBoxContainer/StatusBar/StatusLabel.text = "日志已导出到: " + export_path

# 信号处理函数
func _on_close_button_pressed():
	hide_panel()

func _on_level_option_button_item_selected(index):
	current_filter_level = index
	apply_filters()
	update_status_bar()

func _on_context_line_edit_text_changed(new_text):
	current_filter_context = new_text
	apply_filters()
	update_status_bar()

func _on_search_line_edit_text_changed(new_text):
	current_search_text = new_text
	apply_filters()
	update_status_bar()

func _on_refresh_button_pressed():
	refresh_logs()

func _on_clear_button_pressed():
	# 显示确认对话框
	var dialog = ConfirmationDialog.new()
	dialog.title = "确认清空日志"
	dialog.dialog_text = "确定要清空所有日志吗？此操作不可撤销。"
	dialog.confirmed.connect(func(): clear_logs())
	add_child(dialog)
	dialog.popup_centered()

func _on_export_button_pressed():
	export_logs()
